package org.example;


import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.*;


public class UdpServer implements Runnable {


    Map<String, SocketChannel> channelMap = new HashMap<>();

    @Override
    public void run() {
        try {
            InetSocketAddress broadcast = InetSocketAddress.createUnresolved("255.255.255.255", Config.instance.getWar3Port());

            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            // 设置为非阻塞模式
            serverSocketChannel.configureBlocking(false);
            // 绑定到本地端口
            serverSocketChannel.socket().bind(new InetSocketAddress(Config.instance.getAppUdpPort()));
            // 打开 Selector
            Selector selector = Selector.open();
            // 将 Channel 注册到 Selector，监听 OP_ACCEPT 事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            while (!Thread.interrupted()) {
                // 等待事件
                selector.select();

                // 处理已准备好的事件
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();

                    try {
                        if (key.isAcceptable()) {

                            ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
                            SocketChannel clientChannel = serverChannel.accept();
                            if(clientChannel!=null){

                                ByteBuffer buffer = ByteBuffer.allocate(4);
                                clientChannel.configureBlocking(false);
                                clientChannel.register(selector, SelectionKey.OP_READ, buffer);
                                InetSocketAddress inetSocketAddress = (InetSocketAddress) clientChannel.getRemoteAddress();
                                channelMap.put(inetSocketAddress.toString(), clientChannel);
                            }

                        } else if (key.isReadable()) {
                            ByteBuffer buffer = (ByteBuffer) key.attachment();
                            SocketChannel clientChannel = (SocketChannel) key.channel();
                            InetSocketAddress inetSocketAddress = (InetSocketAddress) clientChannel.getRemoteAddress();

                            if(!clientChannel.isConnected()){
                                clientChannel.close();
                                continue;
                            }

                            int len = -1;
                            try {
                                len = clientChannel.read(buffer);
                            }catch (Exception e){

                            }

                            if (len == -1) {
                                channelMap.remove(clientChannel);
                                clientChannel.close();

                            } else if (len > 0) {

                                if (buffer.limit() == buffer.position()) {
                                    buffer.flip();


                                    if (buffer.limit() == 4) {
                                        int dataLen = buffer.getInt();
                                        System.out.println("address:"+inetSocketAddress+",dataLen:" + dataLen + ",hash:" + clientChannel.hashCode() + ",len:" + len);
                                        ByteBuffer newBuffer = ByteBuffer.allocate(dataLen);
                                        key.attach(newBuffer);

                                    }else if(buffer.limit() == 5){
                                        int port = buffer.getInt();
                                        buffer.get();

                                        ChannelContext.push(port,clientChannel);


                                        ByteBuffer newBuffer = ByteBuffer.allocate(4);
                                        key.attach(newBuffer);

                                    } else {

                                        int anInt = buffer.getInt();
                                        byte[] bt = new byte[anInt];
                                        buffer.get(bt);
                                        String dstAddress = new String(bt);
                                        bt = new byte[buffer.remaining()];
                                        buffer.get(bt);

                                        List<String> removeKey = new ArrayList<>();
                                        for (String address : channelMap.keySet()) {
                                            SocketChannel socketChannel = channelMap.get(address);
                                            if (socketChannel != null && !socketChannel.isConnected()) {
                                                removeKey.add(address);
                                            } else if (socketChannel != null && clientChannel != socketChannel) {

                                                if (dstAddress.equals(broadcast.toString())) {
                                                    //广播
                                                    ByteBuffer buff = buildBuff(inetSocketAddress.toString(), bt);
                                                    socketChannel.write(buff);

                                                } else if (dstAddress.equals(address)) {
                                                    //匹配目标ip
                                                    ByteBuffer buff = buildBuff(inetSocketAddress.toString(), bt);
                                                    socketChannel.write(buff);
                                                }
                                            }
                                        }

                                        for (String k : removeKey) {
                                            channelMap.remove(k);
                                        }

                                        ByteBuffer newBuffer = ByteBuffer.allocate(4);
                                        key.attach(newBuffer);

                                    }
                                }
                            }
                        }
                    }catch(Exception e){
                        SelectableChannel channel = key.channel();

                        channelMap.remove(channel);
                        channel.close();

                        e.printStackTrace();
                    }

                }
            }

        } catch (Exception e) {
            System.out.println("UdpSelector 线程异常结束:" + e.getMessage());
            e.printStackTrace();
        }

    }

    private ByteBuffer buildBuff(String hostAddress, byte[] bt) {
        byte[] bByte = hostAddress.getBytes();
        ByteBuffer allocate = ByteBuffer.allocate(4 + 4 + bByte.length + bt.length);
        allocate.putInt(4 + bByte.length + bt.length);
        allocate.putInt(bByte.length);
        allocate.put(bByte);
        allocate.put(bt);
        allocate.flip();
        return allocate;
    }
}
